/*
 * uart.c
 *
 *  Created on: Apr 15, 2013
 *      Author: Kurt Hardin
 */

#include <msp430.h>

#include "uart.h"
#include "constants.h"


volatile char waiting = 1;

void uartInit(void) {
	UCA0CTL1 |= UCSWRST;
	P1SEL |= BIT1 + BIT2 ;                    // P1.1 = RXD, P1.2=TXD
	P1SEL2 |= BIT1 + BIT2 ;                   // P1.1 = RXD, P1.2=TXD
	UCA0CTL1 |= UCSSEL_2;                     // SMCLK
	UCA0BR0 = 104;                            // 1MHz 9600
	UCA0BR1 = 0;                              // 1MHz 9600
	UCA0MCTL = UCBRS0;                        // Modulation UCBRSx = 1
	UCA0CTL1 &= ~UCSWRST;                     // **Initialize USCI state machine**
	IE2 |= UCA0RXIE;                          // Enable USCI_A0 RX interrupt
}

/**
 * Sends a single byte out through UART
 **/
void uartSendByte(unsigned char byte) {
	while (!(IFG2&UCA0TXIFG));			// USCI_A0 TX buffer ready?		// FIXME Use ISR
	UCA0TXBUF = byte;					// TX -> RXed character
}

/**
 * Sends a string out through UART
 **/
void uartPutS(const char *s) {
	char c;
	while (c = *s++) {			// Get next character
		uartSendByte(c);		// Send character
	}
}

void uartSetWaiting(void) {
	waiting = 1;				// Clear reading flag
}

char uartRxHandler(void) {
	char lpmToExit = 0;
	if (UCA0RXBUF == 'r') {				// If RXed character is an 'r'
		if (waiting) {					// Wakeup uC to take a new reading
			waiting = 0;				// Set reading flag
			uartPutS(LABEL_READ);
			uartPutS(LABEL_NLCR);
			lpmToExit = LPM0_bits;
		}
		else {						// If already reading send "WAIT"
			uartPutS(LABEL_WAIT);
			uartPutS(LABEL_NLCR);
		}
	}
	return lpmToExit;
}
